#include "databaseinterface.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QRegExp>
#include <QStringList>
#include <QSqlTableModel>
#include <QSqlRecord>


DatabaseInterface::DatabaseInterface(QObject *parent):
        Optra::ZoneInterface(parent)
{
    info_ = new Optra::ZoneInfo("databaseZone", "Database");
}

DatabaseInterface::~DatabaseInterface(void)
{
    delete info_;
}

void DatabaseInterface::setRegisterScope(const QVariant& val)
{
    QMap<QString, QVariant> s = val.toMap();
    QString dbname = s["sender"].toString();
    QString scope = s["scope"].toString();
    QSqlDatabase db = QSqlDatabase::database(dbname);

    QMap<QString, QVariant> data = s["data"].toMap();

     if (!db.tables().contains(scope)){
        QSqlQuery query(db);

        QStringList dataStream;
        foreach (QVariant v, data.values()){
            dataStream << v.toString();
        }

        if (!query.exec("CREATE TABLE " + scope + " (" + dataStream.join(",") + ")")){
            qDebug() << query.lastError().text();
        }
    }

}

void DatabaseInterface::setRegisterDatabase(const QString& dbname)
{
    qDebug() << "Create Database";
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", dbname);
    db.setDatabaseName(dbname);
    bool o = db.open();
    if (!o) {
        QMessageBox::critical(0, ("Cannot open database"),
                              ("Unable to establish a database connection.\n"
                               "This zone needs SQLite support. Please read "
                               "the Qt SQL driver documentation for information how "
                               "to build it.\n\n"
                               "Click Cancel to exit."), QMessageBox::Cancel);
        return;
    }
}

QVariant DatabaseInterface::save()const
{
    return QVariant(save_);
}
void DatabaseInterface::setSave(const QVariant& val)
{
    QMap<QString, QVariant> s = val.toMap();
    save_.clear();
    QString dbname = s["sender"].toString();
    QString scope = s["scope"].toString();
    QSqlDatabase db = QSqlDatabase::database(dbname);

    QMap<QString, QVariant> data = s["data"].toMap();

//    QSqlTableModel tm(this, db);
//    tm.setTable(scope);
//    tm.setEditStrategy(QSqlTableModel::OnManualSubmit);
//
//    tm.select();

   // (tm.rowCount() > 1)

    QStringList names, values;
    names = data.keys();


    values = names;
    values.replaceInStrings(QRegExp("^"), ":");

    QString queryStr = "INSERT INTO " + scope + " ( " + names.join(", ") + ") VALUES (" + values.join(", ") + " )";
    QSqlQuery query(db);
    query.prepare(queryStr);

    foreach(QString k, names) {
  //      tm.in
        query.bindValue(":" + k, data[k]);
    }

    if (!query.exec()){
        qDebug() << query.lastError().text();
    }


    qDebug() << "Database:Save Property";
}

QList<QVariant> DatabaseInterface::values()const
{
    return values_;
}

void DatabaseInterface::setValues(const QList<QVariant>& val)
{
    values_.clear();
    if (val.size() < 3){
        return;
    }
    QString zoneName = val.at(0).toString();
    if (zoneName != "community"){
        return;
    }

    QString key = val.at(1).toString();
    if (key != "user"){
        return;
    }
    key = val.at(2).toString();

    if (key != "password"){
        return;
    }

    QSqlDatabase db = QSqlDatabase::database(zoneName);
    QSqlQuery query("SELECT username, password FROM settings", db);
    query.exec();



    while (query.next()) {
        QString user = query.value(0).toString();
        QString pass = query.value(1).toString();
        values_.append(user);
        values_.append(pass);
        break;
    }
}

Optra::ZoneInfo* DatabaseInterface::zoneInfo()
{
   return info_;
}

bool DatabaseInterface::configure(bool read)
{
    return true;
}

bool DatabaseInterface::initialize()
{
    return true;//createConnection();
}

void DatabaseInterface::launch()
{
    qDebug() << "Database launch";
}

void DatabaseInterface::unload()
{

}

void DatabaseInterface::functionx(QString name)
{
    qDebug() << "Database function:" << name;
    //return true;
}
